﻿using System;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using ExceptionLogger;
namespace DataImportService
{
    class Program
    {
        static string connectionString = ConfigurationManager.ConnectionStrings["CMT"].ConnectionString;
        static string importStatus = "Success";
        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString());
            DirectoryServer admServer = null;
            DataTable dtusers = null;
            DataImportDAC objDataImport = null;
            int recordsCount, countryRecordsCount;
            ExceptionManager ex = ex = new ExceptionManager();
            try
            {                
                objDataImport = new DataImportDAC(connectionString);
                //Get last pulled date from table
                DateTime? lastADAMImportDate = objDataImport.getLastLDAPImportDate();

                if (!lastADAMImportDate.HasValue)
                {
                    //Get countryList
                    DataTable countryList = GetCountries();

                    //Save country
                    if (countryList != null)
                    {

                        ex.Publish("Succesfully retrieved countries!");
                        ex.Publish("Importing data in to country table!");
                        //Import data into a country table 

                        if (objDataImport.ImportCountryData(countryList, out countryRecordsCount))
                        {
                            ex.Publish("Succesfully imported data in to country table");
                            ex.Publish("Number of Records Inserted: " + countryRecordsCount);
                        }
                        else
                        {
                            importStatus = "Failed";
                            ex.Publish("Failed to import data into country table!");
                        }
                    }
                    else
                    {
                        ex.Publish("No Country Records retrieved!");
                    }
                }
                ex.Publish("Started retieving from ADAM!");
                admServer = new DirectoryServer();
                dtusers = admServer.GetAllEmployee(lastADAMImportDate);
              
                if (dtusers != null)
                {
                    ex.Publish("Succesfully retrieved data from ADAM!");
                    ex.Publish("Importing data in to staging table!");

                    //Import data into a staging table 
                    if (objDataImport.BulkImportToEmployeeStagingData(dtusers))
                    {
                        ex.Publish("Succesfully imported data in to staging table!");
                        ex.Publish("Importing data in to CMT_Employee table!");

                        //Update the CMT_Employee table with info from staging table
                        if (objDataImport.UpdateEmployeeData(out recordsCount))
                        {
                            ex.Publish("Succesfully imported data in to CMT_Employee table!");
                            ex.Publish("Number of Records Affected: " + recordsCount);

                        }
                        else
                        {
                            importStatus = "Failed";
                            ex.Publish("Failed to import data in to CMT_Employee table!");
                        }

                    }
                    else
                    {
                        importStatus = "Failed";
                        ex.Publish("Failed to import data into staging table. Could not start data import to CMT_Employee table!");
                    }
                }
                else
                {
                    importStatus = "NoRecords";
                    ex.Publish("No Records retrieved from ADAM!");
                }
                Console.WriteLine("Process Completed!");
                ex.Publish("Process Completed!");
                Console.WriteLine(DateTime.Now.ToLongTimeString());

            }
            catch (Exception exc)
            {
                importStatus = "Failed";
                ex.Publish(exc.Message);
            }
            finally
            {
                admServer = null;
                dtusers = null;
                objDataImport = null;
                ex = null;
            }
            Console.Out.WriteLine(importStatus);
        }

        class Country
        {
            public string CountryId { get; set; }
            public string Title { get; set; }
        }
        static DataTable GetCountries()
        {
            DataTable dtCountryList = null;
            DataRow dr;
            IEnumerable<IGrouping<string, RegionInfo>> countryList = from ri in
                                                                         from ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                                                                         select new RegionInfo(ci.LCID)
                                                                     group ri by ri.TwoLetterISORegionName into g
                                                                     select g;

            dtCountryList = new DataTable();
            dtCountryList.TableName = "Country";
            dtCountryList.Columns.Add("DESCRIPTION", typeof(string));
            dtCountryList.Columns.Add("COUNTRY", typeof(string));
            dtCountryList.Columns.Add("COUNTRY_2CHAR", typeof(string));
            dtCountryList.Columns.Add("Currency", typeof(string));

            foreach (IGrouping<string, RegionInfo> countryInfo in countryList)
            {
                dr = dtCountryList.NewRow();
                dr["Currency"] = countryInfo.First().ISOCurrencySymbol;
                dr["COUNTRY"] = countryInfo.First().ThreeLetterISORegionName;
                dr["COUNTRY_2CHAR"] = countryInfo.First().TwoLetterISORegionName;
                dr["DESCRIPTION"] = countryInfo.First().DisplayName;
                dtCountryList.Rows.Add(dr);
            }
            return dtCountryList;
        }

    }
}
